package cn.hmcode.service;

import cn.hmcode.config.AnythingLLMConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

@Service
public class AnythingLLMService {

    @Autowired
    private AnythingLLMConfig config;

    @Autowired
    private RestTemplate restTemplate;

    public String sendPrompt(String prompt,String workspace) {
        String url = config.getApiUrl() + "/v1/workspace/"+workspace+"/chat";

        // 使用 Fastjson 构建请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("message", prompt);
        requestBody.put("mode","query");
        requestBody.put("sessionId",8);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + config.getApiKey());

        HttpEntity<String> request = new HttpEntity<>(requestBody.toJSONString(), headers);

        // 发送请求
        ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
        // 转换为UTF8
        String s = new String(response.getBody().getBytes(StandardCharsets.UTF_8));
        if (response.getStatusCode() == HttpStatus.OK) {
            // 使用 Fastjson 解析响应
            JSONObject responseBody = JSON.parseObject(s);
            String string = responseBody.getString("textResponse");
            //string = string.replaceAll("<think>","").replaceAll("</think>","");
            System.out.println(string);
            return string; // 假设响应中包含 "response" 字段
        } else {
            throw new RuntimeException("Failed to get response from AnythingLLM: " + response.getStatusCode());
        }
    }
}
